<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

  <title>大话骰</title>
  <link rel="stylesheet" href="index.css">

</head>
<body>

<div class="dice-main" id="diceMain">
  <div class="dice-cover" id="diceCover" style="transform:translateY(-80%)" onclick="handleCover()"></div>

  <div class="dices" id="dices"></div>

  <div class="dice-base"></div>

</div>

<div style="display: grid;grid-template-columns: repeat(2, 1fr); gap: 10px;margin-bottom: 20px;">
  <button class="btn openCloseBg" id="openCoverB" onclick="handleCover()">关盅</button>
  <button class="btn" id="shakeDiceB" onclick="shakeDice()">摇骰子🎲</button>
  <button class="btn" onclick="calculate()">结果(开)</button>
  <button class="btn prohibitBg" onclick="doNotRollDice(this)">禁止摇骰🚫</button>
</div>

<div id="result"></div>
<div id="resultSpecial"></div>

<!-- 一些无足轻重的按钮 -->
<div style="margin-top: 10px">
  <div>
    <label for="openMp3Check">开盅杨戬音效</label>
    <input type="checkbox" id="openMp3Check" checked/>
  </div>

  <div>
    <label for="semiTransparent">骰盅半透明</label>
    <input type="checkbox" id="semiTransparent" onclick="handleTransparency(this)"/>
  </div>

  <div>
    <label for="noAutoCover">摇骰子不自动盖盅</label>
    <input type="checkbox" id="noAutoCover"/>
  </div>

  <div>
    <a href="./dice-rules.html">基本说明</a>
  </div>
</div>


</body>

<script>
  // 提前加载音效
  const openMp3 = new Audio('./open.mp3');
  const diceMp3 = new Audio('./dice.mp3');
  let isCoverOpen = true;     // 骰盅开关状态
  let isNotRollDice = false;  // 是否禁止摇骰子

  const diceMain = document.getElementById('diceMain')            // 骰子全部
  const diceCover = document.getElementById('diceCover')          // 骰盅
  const dices = document.getElementById('dices')                  // 骰子容器
  const openCoverB = document.getElementById('openCoverB')        // 骰盅开关按钮
  const shakeDiceB = document.getElementById('shakeDiceB')        // 摇骰子按钮
  const result = document.getElementById('result')                // 开的结果
  const resultSpecial = document.getElementById('resultSpecial')  // 开的结果(特殊
  const playOpenMp3 = document.getElementById('openMp3Check');    // 勾选 是否播放开骰盅音效(杨戬大叫:开!!!
  const noAutoCover = document.getElementById('noAutoCover');     // 勾选 是否自动盖盖子

  shakeDice(true) // 初始化骰子

  /**
   * 摇骰子逻辑
   * @param {boolean} isInit 是否是初始化
   *
   * @author 𝓒𝓱𝓮𝓷𝓖𝓾𝓪𝓷𝓰𝓛𝓸𝓷𝓰
   * @since 2025/9/15 2:42
   */
  function shakeDice(isInit = false) {
    let diceNumbers = Array(5).fill(0)
    if (!isInit) {
      shakeDiceB.disabled = true          // 禁用按钮
      if (!noAutoCover.checked) handleCover(isCoverOpen = true)     // 关闭骰盅
      diceMain.classList.add('shaking');  // 添加摇动动画
      diceMp3.play()                      // 播放骰子音效
      diceNumbers = diceNumbers.map(() => Math.floor(Math.random() * 6) + 1).sort()
      result.innerHTML = '';
      resultSpecial.innerHTML = '';
    }

    window.setTimeout(() => {
      dices.innerHTML = '';
      diceNumbers.forEach(diceNumber => {
        const dice = document.createElement('img')
        dice.src = `./dice-svg/${diceNumber}.svg`
        dices.appendChild(dice)
        shakeDiceB.disabled = false
      })
    }, 200)

    // 2秒后停止摇动
    setTimeout(() => {
      diceMain.classList.remove('shaking');
    }, 1000);

  }

  /**
   * 处理骰盅开关
   *
   * @author 𝓒𝓱𝓮𝓷𝓖𝓾𝓪𝓷𝓰𝓛𝓸𝓷𝓰
   * @since 2025/9/15 2:58
   */
  function handleCover() {
    if (isCoverOpen) {
      openCoverB.innerText = '打开盅'
      diceCover.style.transform = 'translateY(0)'
    } else {
      diceCover.style.transform = 'translateY(-80%)'
      openCoverB.innerText = '关盅'
    }
    isCoverOpen = !isCoverOpen
  }

  /**
   * 计算逻辑
   *
   * @author 𝓒𝓱𝓮𝓷𝓖𝓾𝓪𝓷𝓰𝓛𝓸𝓷𝓰
   * @since 2025/9/15 2:58
   */
  function calculate() {
    if (playOpenMp3.checked) openMp3.play()
    handleCover(isCoverOpen = false)
    const resultCountMap = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0}

    // 拿到全部数字(从url里面切割出来
    dices.querySelectorAll('img').forEach(dice => {
      const diceNumber = Number(dice.src.match(/\/dice-svg\/(\d+)\.svg/)[1])
      resultCountMap[diceNumber]++
    })

    delete resultCountMap[0]; // 删除 0 的ksy

    const entries = Object.entries(resultCountMap);
    const oneNumber = resultCountMap[1];

    // 检查是否没摇（全是0)
    if (entries.every(([_key, value]) => value === 0)) {
      return resultSpecial.innerHTML = `先摇啦~`
    }

    // 检查是否是纯豹  豹子又叫围骰
    const findPureLeopard = entries.find(([_key, value]) => value === 5);
    if (findPureLeopard) {
      return resultSpecial.innerHTML = `🐆纯豹<img src="./dice-svg/${findPureLeopard[0]}.svg" alt=""/>5+2个`
    }
    // 检查是否是豹子
    if (resultCountMap[1] !== 0) {  // 首先，报纸的概念一肯定不能为零[条件可忽略
      const findLeopard = entries.find(([key, value]) => {
        if (key === "1") return false;  // 当然不可以为1   条件可忽略：1加本身只能是偶数，不可能等于五
        return value + oneNumber === 5
      });
      if (findLeopard) {
        return resultSpecial.innerHTML = `🐆豹子<img src="./dice-svg/${findLeopard[0]}.svg" alt=""/>(${findLeopard[1]}+${oneNumber})+1个`
      }
    }
    // 检查是否是顺子(顺子，就是5颗骰子，没有相同的，就是顺子:::就是列表的value全部要<=1)
    if (entries.every(([_key, value]) => value <= 1)) {
      return resultSpecial.innerHTML = `顺骰(重摇或归0)`
    }

    /** 计算有1的特殊情况，给的样式 */
    const addOneNumber = (iKey) => {
      if (oneNumber === 0 || iKey === 1) return resultCountMap[iKey]
      let keyNun = resultCountMap[iKey] === 0 ? '' : `<b>${resultCountMap[iKey]}</b><span style="color: #4bafab">+</span>`
      return `${keyNun}<span style="color: red">${oneNumber}</span>`
    }

    // 输出非0个的结果
    let resultText = '';
    for (let i = 1; i <= 6; i++) {
      if (resultCountMap[i] > 0 || oneNumber > 0) {
        resultText += `
          <div>
            <img src="./dice-svg/${i}.svg" alt=""/>
            <div>${addOneNumber(i)}</div>
          </div>`;
      }
    }
    if (oneNumber > 0) result.style.gridTemplateColumns='repeat(6, 1fr)'
    else result.style.gridTemplateColumns = `repeat(${entries.filter(([_, value]) => value > 0).length}, 1fr)`
    result.innerHTML = resultText;
  }

  /**
   * 禁止摇骰子按钮点击事件
   *
   * @author 𝓒𝓱𝓮𝓷𝓖𝓾𝓪𝓷𝓰𝓛𝓸𝓷𝓰
   * @since 2025/9/15 2:58
   */
  function doNotRollDice(e) {
    if (isNotRollDice) {
      isNotRollDice = false;
      shakeDiceB.classList.remove('prohibit');
      e.innerText = '禁止摇骰🚫'

    } else {
      isNotRollDice = true;
      shakeDiceB.classList.add('prohibit');
      e.innerText = '允许摇骰⭕'
    }
  }

  /**
   * 骰盅半透明
   *
   * @author 𝓒𝓱𝓮𝓷𝓖𝓾𝓪𝓷𝓰𝓛𝓸𝓷𝓰
   * @since 2025/9/15 22:03
   */
  function handleTransparency(checkbox) {
    if (checkbox.checked) diceCover.style.background = 'radial-gradient(#ffffffad 0%, #000000d4 100%)';
    else diceCover.style.background = 'radial-gradient(#fff 0%, #000 100%)';
  }

</script>
</html>